<template>
  <div class="index-container pb-10">
    <section class="bg-linear"
      id="linear">
      <div class="max-w-8xl mx-auto px-4 pt-11 pb-10 sm:px-6 lg:px-4">
        <h1 class="title text-center text-gray-1000 break-words font-semibold xl:-mx-4">{{$t('gpts_discoverGPTsStore')}}</h1>

        <p class="desc text-center text-purple-1300 mt-4 break-words">{{$t('gpts_GPTsFromGPTStore')}}</p>
        <div class="mb-3 mt-10 max-w-5xl mx-auto md:px-4">
          <common-search></common-search>
        </div>
      </div>
    </section>

    <div class="max-w-11xl px-4 pt-12 pb-9 mx-auto">
      <p class="text-base text-gray-1000">
        <span>
          {{$t('gpts_GPTsFoundAndCounting')}}
        </span>
        &nbsp;
        <common-link path="/submit"
          class="inline-flex items-center text-purple-1300 hover:opacity-90">
          <span>
            {{$t('gpts_submitYourAwesomeGPT')}}
          </span>
          <svg-icon iconName="arrow_right_purple"
            className="text-sm ml-2"></svg-icon>
        </common-link>
      </p>
      <div class="tools grid gap-5 sm:grid-cols-2 md:grid-cols-3 mt-7"
        v-if="toolsList && toolsList.length > 0">
        <gpts-tool v-for="(item, key) in toolsList"
          :key="item.handle+'-'+key"
          :toolsData="item"></gpts-tool>
      </div>
      <div class="w-2/4 mx-auto mt-16 text-center"
        v-if="toolsList && toolsList.length>0">
        <el-button type="text"
          v-if="next_page_url"
          class="cursor-default">
          <img src="@/static/images/loading.png"
            class="loading"
            alt=""
            srcset="">
        </el-button>

        <el-divider v-else>
          <el-button type="text"
            class="cursor-default"
            :loading="loading">{{ $t('end') }}</el-button>
        </el-divider>
      </div>
      <el-empty v-else
        :description="$t('noData')"></el-empty>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
export default {
  name: 'GPTs',
  head() {
    return {
      htmlAttrs: {
        lang: this.locale,
      },
      title: this.title,
      meta: [
        {
          hid: 'description',
          name: 'description',
          content: this.description,
        },
        {
          hid: 'og:title',
          name: 'og:title',
          content: this.title,
        },
        {
          hid: 'og:description',
          name: 'og:description',
          content: this.description,
        },
        {
          hid: 'og:url',
          name: 'og:url',
          content: this.canonicalLink,
        },
        {
          hid: 'og:image:alt',
          name: 'og:image:alt',
          content: this.title,
        },
      ],
      link: [
        {
          rel: 'canonical',
          href: this.canonicalLink,
        },
      ],
    }
  },
  async asyncData({ app, route, params, query, $axiosApi, error }) {
    try {
      let searchRes = await $axiosApi.chatgpts({
        page: 1,
        per_page: 24,
        keyword: query.keyword,
      })

      let res = {}
      if (searchRes.code === 200) {
        res.new_list = searchRes.data.new_list
        res.toolsList = searchRes.data.data
        res.category_group_list = searchRes.data.category_group_list

        res.total = searchRes.data.total
        res.page = searchRes.data.current_page ? searchRes.data.current_page : 1
        res.next_page_url = searchRes.data.next_page_url
          ? searchRes.data.next_page_url
          : null

        res.tool_count = searchRes.data.tool_count
        res.category_count = searchRes.data.category_count
      } else {
        if (searchRes && searchRes.code && searchRes.code === 404) {
          error({ statusCode: 404 })
        } else if (!(searchRes && searchRes.code && searchRes.code === 401)) {
          error({
            message:
              'There is a problem with the network. Please refresh and try again later',
            statusCode: searchRes.code,
          })
        }
      }

      let description = app.i18n.t('gpts_list_pageDesc')
      let title = app.i18n.t('gpts_list_pageTitle')

      return {
        ...res,
        title,
        description,
      }
    } catch (err) {
      console.log(err)
    }
  },
  watch: {
    $route: {
      handler(route) {
        /* if (route.name === this.$route.name) {
          this.getList(1)
        } */
      },
      deep: true,
    },
  },
  data() {
    return {
      canonicalLink: `https://www.toolify.ai${this.$route.fullPath}`,
      title: null,
      description: null,

      new_list: [],
      toolsList: [],
      category_group_list: [],
      page: 1,
      per_page: 24,
      next_page_url: null,
      loading: false,
      total: 0,

      tool_count: 0,
      category_count: 0,
    }
  },
  computed: {
    ...mapState({
      countries: (state) => state.countries,
      locale: (state) => state.locale,
    }),
  },
  mounted() {
    window.addEventListener('scroll', this.onSroll)
  },
  methods: {
    ...mapMutations(['SET_RetrackExposure']),
    onSroll() {
      var scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop
      //变量windowHeight是可视区的高度
      var windowHeight =
        document.documentElement.clientHeight || document.body.clientHeight
      //变量scrollHeight是滚动条的总高度
      var scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight

      const footerHeight = document.querySelector('footer').offsetHeight

      //滚动条到底部的条件
      if (scrollTop + windowHeight + 1200 > scrollHeight - footerHeight) {
        if (this.next_page_url && !this.loading) {
          this.getList(this.page + 1)
        }
      }
    },
    async getList(page) {
      this.loading = true
      try {
        const res = await this.$axiosApi.chatgpts({
          page: page,
          per_page: 24,
          keyword: this.$route.query.keyword,
        })

        this.loading = false

        if (res.code === 200) {
          if (page === 1) {
            this.toolsList = res.data.data
          } else {
            this.toolsList = this.toolsList.concat(res.data.data)
          }
          this.total = res.data.total ? res.data.total : 0
          this.page = res.data.current_page ? res.data.current_page : 1
          this.next_page_url = res.data.next_page_url
            ? res.data.next_page_url
            : null
          this.SET_RetrackExposure(Date.now())
        }
      } catch (error) {
        console.log('error')
        this.loading = false
      }
    },
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.onSroll, false)
  },
}
</script>
<style lang='scss' scoped>
.index-container {
  .title {
    font-size: 58px;
    line-height: 72px;
  }
  .desc {
    font-size: 20px;
    line-height: 26px;
    color: #6339d6;
  }
}
</style>
